package com.yxjx.duoxue.customview;
import java.util.ArrayList;

import com.yxjx.duoxue.R;
import com.yxjx.duoxue.datamodel.DMArea;
import com.yxjx.duoxue.datamodel.DMCourseCategory;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;


public class TwoColumnListView<E> extends LinearLayout {
	
	/**
	 * Following data is used to demonstrate the structure of data.
	 * 第一列是一级分类；
	 * 每一行第二个是指二级分类不限制，之后是详细的二级分类项。
	 */
	private String[][] mData = new String[][] {
			{"启蒙教育", "全部", "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部",  "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"},
			{"启蒙教育", "全部",  "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部", "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"},
			{"启蒙教育", "全部",  "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部", "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"},
			{"启蒙教育", "全部",  "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部", "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"},
			{"启蒙教育", "全部",  "脑神经","托儿班","多元智能","趣味数学"},
			{"舞蹈乐器", "全部",  "自信力","社交力","适应力","亲子教育"},
			{"书法国学", "全部", "软笔书法","硬笔书法","综合书法","国学","篆刻","礼仪"}
	};
	private ArrayList<ArrayList<E>> mAllData = new ArrayList<ArrayList<E>>();
	private ArrayList<E> mColumn1Data;
	private ArrayList<ArrayList<E>> mColumn2Data;
	
	// record user's selection on column 1 and 2.
	private int mColumn1Selected = -1;
	private int mColumn2Selected = -1;
	
	// inital user's selection at last time.
	private int mColumn1LastSelected = -1;
	private int mColumn2LastSelected = -1;
	
	private void initData() {
		if (mAllData == null) {
			return;
		}
		mColumn1Data = new ArrayList<E>();
		mColumn2Data = new ArrayList<ArrayList<E>>();
		for (int i = 0; i < mAllData.size(); i++) {
			ArrayList<E> level1 = mAllData.get(i);
			ArrayList<E> row = new ArrayList<E>();
			
			for (int j = 0; j < level1.size(); j++) {
				if (j == 0) {
					mColumn1Data.add(level1.get(j));
					mColumn2Data.add(row);
					Log.d("CMM", "column1 add to row data[i][j] = " + level1.get(j));
				} else {
					row.add(level1.get(j));
					Log.d("CMM", "column2 add to row data[i][j] = " + level1.get(j));
				}
			}
		}
	}

	public TwoColumnListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		LayoutInflater.from(context).inflate(R.layout.segment_two_column_list, this, true);
		initData();
		refreshList1();
	}

	private void refreshList1() {
		mList = (ListView) findViewById(R.id.list1);
		mColumn1Adapter = new Column1Adapter(mColumn1Data, mColumn1LastSelected);
		mList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mList.setAdapter(mColumn1Adapter);
		// 用来调整选中项在list中的位置（默认选中第四个的位置）。
		mList.setSelection(mColumn1LastSelected < 3 ? 0 : mColumn1LastSelected - 3);
		mList.setOnItemClickListener(mItemClickListener1);
		mList.postDelayed(new Runnable() {
			@Override
			public void run() {
				// 模拟一次点击选择项的动作。(如果最后一次选择的column1Index == 0, do nothing)
				if (mColumn1LastSelected > 0) {
					mItemClickListener1.onItemClick(null, null, mColumn1LastSelected, 0);
				}
			}
		}, 0);
	}

	public void setCallback(CallbackForSelection mCallback) {
		this.mCallback = mCallback;
	}

	AdapterView.OnItemClickListener mItemClickListener1 = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg00, View arg11, int arg2,
				long arg33) {
			// 
			if (arg2 < 0) {
				return;
			}
			mColumn1Selected = arg2;
			// 第一列第一项为全部（忽略）
			if (arg2 == 0) {
				if (mCallback != null) {
					mCallback.selected(mColumn1Selected, mColumn2Selected);
				}
				return;
			}
			ListView list = (ListView) findViewById(R.id.list2);
			int initColumn2Index = -1;
			if (mColumn1LastSelected == arg2) {
				initColumn2Index = mColumn2LastSelected;
			}
			Column2Adapter adapter = new Column2Adapter(mColumn2Data.get(arg2), initColumn2Index);
			list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			list.setAdapter(adapter);
			list.setOnItemClickListener(mItemClickListener2);
			// 用来调整选中项在list中的位置（默认选中第四个的位置）。
			list.setSelection(mColumn2LastSelected < 3 ? 0 : mColumn2LastSelected - 3);
			//Toast.makeText(getContext(), "setSelection index = " + arg2, Toast.LENGTH_SHORT).show();
			adapter.notifyDataSetChanged();
			mColumn1Adapter.setSelectedIndex(mColumn1Selected);
			mColumn1Adapter.notifyDataSetInvalidated();
			
			
		}
	};
	
	AdapterView.OnItemClickListener mItemClickListener2 = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			
			mColumn2Selected = arg2;
//			Toast.makeText(getContext(),
//					"selected tab1 = " + mColumn1Selected + ", tab2 = "
//							+ mColumn2Selected, Toast.LENGTH_SHORT).show();
			if (mCallback != null) {
				mCallback.selected(mColumn1Selected, mColumn2Selected);
			}
			
		}
	};
	
	class Column1Adapter extends BaseAdapter {
		
		private ArrayList<E> mDataList;
		private int mSelectedIndex = -1;
		
		public Column1Adapter(ArrayList<E> data, int selected) {
			mDataList = data;
			mSelectedIndex = selected;
		}
		
		@Override
		public int getCount() {
			return mDataList == null ? 0 : mDataList.size();
		}
		
		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (arg1 == null) {
				ret = LayoutInflater.from(getContext()).inflate(R.layout.item_search_condition, null);
			} else {
				ret = arg1;
			}
			E item = mDataList.get(arg0);
			if (item instanceof DMArea) {
				UIHelper.setText(ret, R.id.text, ((DMArea) item).getAreaName());
			} else if (item instanceof DMCourseCategory) {
				UIHelper.setText(ret, R.id.text, ((DMCourseCategory) item).getStr());
			}
			Utils.logd("CMM5 adapter1 arg0 = " + arg0 + ", mSelectedIndex = " + mSelectedIndex);
			ret.findViewById(R.id.text).setSelected(arg0 == mSelectedIndex);
//			ret.setBackgroundColor(arg0 == mSelectedIndex ? Color.RED : Color.WHITE);
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		public ArrayList<E> getDataList() {
			return mDataList;
		}

		public void setDataList(ArrayList<E> mDataList) {
			this.mDataList = mDataList;
		}

		public int getSelectedIndex() {
			return mSelectedIndex;
		}

		public void setSelectedIndex(int selectedIndex) {
			this.mSelectedIndex = selectedIndex;
		}

	}
	
	// re-fill Two colum list's data.
	/**
	 * 
	 * @param data
	 * @param column1Selected
	 * @param column2Selected
	 */
	public void setData(ArrayList<ArrayList<E>> data, int column1Selected, int column2Selected) {
		mColumn1LastSelected = column1Selected;
		mColumn2LastSelected = column2Selected;
		mAllData = data;
		initData();
		refreshList1();
	}
	
	class Column2Adapter extends BaseAdapter {
		
		private ArrayList<E> mDataList;
		private int mSelectedIndex = -1;
		
		public Column2Adapter(ArrayList<E> data, int selected) {
			mDataList = data;
			mSelectedIndex = selected;
		}
		
		@Override
		public int getCount() {
			return mDataList == null ? 0 : mDataList.size();
		}
		
		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (arg1 == null) {
				ret = LayoutInflater.from(getContext()).inflate(R.layout.item_search_condition_2, null);
			} else {
				ret = arg1;
			}
			E item = mDataList.get(arg0);
			if (item instanceof DMCourseCategory) {
				UIHelper.setText(ret, R.id.text, ((DMCourseCategory) item).getStr());
			} else if (item instanceof DMArea) {
				UIHelper.setText(ret, R.id.text, ((DMArea) item).getAreaName());
			}
			Utils.logd("CMM5 adapter2 arg0 = " + arg0 + ", mSelectedIndex = " + mSelectedIndex);
			ret.findViewById(R.id.text).setSelected(arg0 == mSelectedIndex);
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		public ArrayList<E> getDataList() {
			return mDataList;
		}

		public void setDataList(ArrayList<E> mDataList) {
			this.mDataList = mDataList;
		}

		public int getSelectedIndex() {
			return mSelectedIndex;
		}

		public void setSelectedIndex(int selectedIndex) {
			this.mSelectedIndex = selectedIndex;
		}

	}
	
	// 用户点选择时，Activity中更新query结果
	public interface CallbackForSelection {
		public void selected(int column1, int column2);
	}
	
	private CallbackForSelection mCallback;
	private ListView mList;
	private Column1Adapter mColumn1Adapter;
	
}
